package com.youi.third.wechat.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.alibaba.fastjson.JSONObject;
import com.youi.third.wechat.model.AccessToken;

/**
 * 小程序海报二维码生成工具
 * @author XJY
 *
 */
public class MiniAppPoster {

	// 图片的宽度
	private static int width = 140;
	// 图片的高度。
	private static int height =140;
	
	/**
	 * 生成分享海报
	 * @param accessToken 用户accessTokn
	 * @param xcxPath 要跳转的链接
	 * @param avatarUrl 用户头像
	 * @param original 背景图片
	 * @return
	 */
	public static BufferedImage createPoster(String accessToken,String xcxPath,String avatarUrl,String original) {		
		try {
			//第一步加载底图
			URL url = new URL(original);
			BufferedImage backgroud=ImageIO.read(url);
			//第二步加载头像,把头像拼到底图上
			url = new URL(avatarUrl);
			BufferedImage imgUrlImage=ImageIO.read(url);
			imgUrlImage=scaleByPercentage(imgUrlImage, width, height);
			imgUrlImage=convertCircular(imgUrlImage);
			Graphics2D g = backgroud.createGraphics();
			g.drawImage(imgUrlImage.getScaledInstance(140, 140, Image.SCALE_DEFAULT), 293, 120, null);
			g.dispose();
			//第三步加载二维码拼接到底图上
			BufferedImage qrCodeImage=getQrCode(accessToken, xcxPath, 280);
			g = backgroud.createGraphics();
			g.drawImage(qrCodeImage.getScaledInstance(width, height, Image.SCALE_DEFAULT), 279, 950, null);
			g.dispose();
            return backgroud;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 生成小程序二维码
	 * @param accessToken
	 * @param xcxPath
	 * @param width
	 * @return
	 */
    public static BufferedImage getQrCode(String accessToken,String xcxPath, int width) {
        String createwxaqrcodeStr = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
        InputStream is = null;
        try {
            JSONObject json = new JSONObject();
            json.put("path",xcxPath);
            json.put("width",width);
            String params = json.toString();
            is = postInputStream(createwxaqrcodeStr, params);
            BufferedImage image = ImageIO.read(is);
            Graphics2D g2 = image.createGraphics();
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
 
    /**
     * 发送HttpPost请求 返回流
     *
     * @param strUrl 服务地址
     * @param params json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
     * @return 成功:返回json字符串<br/>
     */
    public static InputStream postInputStream(String strUrl, String params) {
        try {
            // 创建连接
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置接收数据的格式
            connection.setRequestProperty("Accept", "application/json");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json");
            //创建链接
            connection.connect();
            // utf-8编码
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            out.append(params);
            out.flush();
            out.close();
            return connection.getInputStream();
 
        } catch (IOException e) {
 
            e.printStackTrace();
        }
        return null;
    }
 
 
 
    /**
	 * 传入的图像必须是正方形的 才会 圆形 如果是长方形的比例则会变成椭圆的
	 * 
	 * @param url 用户头像地址
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage convertCircular(BufferedImage bi1) throws IOException {
		// 透明底的图片
		BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
                BufferedImage.TYPE_INT_BGR);
		Image image = (Image) bi1;
		ImageIcon imageIcon = new ImageIcon(image);
        Graphics2D g2 = bi2.createGraphics();
        g2.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
        int alpha = 0;
        for (int j1 = bi1.getMinY(); j1 < bi1.getHeight(); j1++) {
            for (int j2 = bi1.getMinX(); j2 < bi1.getWidth(); j2++) {
                int rgb = bi1.getRGB(j2, j1);

                int R = (rgb & 0xff0000) >> 16;
                int G = (rgb & 0xff00) >> 8;
                int B = (rgb & 0xff);
                if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
                    rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
                }
                bi1.setRGB(j2, j1, rgb);
            }
        }
        g2.drawImage(bi1, 0, 0, imageIcon.getImageObserver());
        g2.dispose();
		return bi2;
	}
	
	
	
	public static BufferedImage roundImage(BufferedImage image, int targetSize, int cornerRadius) {
        BufferedImage outputImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = outputImage.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize, cornerRadius, cornerRadius));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return outputImage;
    }
    /**
     * 生成圆角图标
     * @param image
     * @param cornerRadius 圆角半径
     * @return
     */
    public static BufferedImage makeRoundedCorner1(BufferedImage image, int cornerRadius) {
        int w = image.getWidth();
        int h = image.getHeight();
        BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = output.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return output;
    }
    /**图片圆角处理，背景透明化
     * @param srcImageFile 原图片
     * @param result  处理后图片
     * @param type   图片格式
     * @param cornerRadius  720为圆角
     */
    public  void makeRoundedCorner(File srcImageFile, File result, String type, int cornerRadius) {
        try {
            BufferedImage bi1 = ImageIO.read(srcImageFile);

            // 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
            BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);

            Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
                    .getHeight());

            Graphics2D g2 = image.createGraphics();
            image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT);
            g2 = image.createGraphics();
            g2.setComposite(AlphaComposite.Clear);
            g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
            g2.setClip(shape);
            // 使用 setRenderingHint 设置抗锯齿
            g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.fillRoundRect(0, 0,bi1.getWidth(), bi1.getHeight(), cornerRadius, cornerRadius);
            g2.setComposite(AlphaComposite.SrcIn);
            g2.drawImage(bi1, 0, 0, bi1.getWidth(), bi1.getHeight(), null);
            g2.dispose();
            ImageIO.write(image, type, result);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }


	/**
	 * 缩小Image，此方法返回源图像按给定宽度、高度限制下缩放后的图像
	 * 
	 * @param inputImage
	 * @param maxWidth
	 *            ：压缩后宽度
	 * @param maxHeight
	 *            ：压缩后高度
	 * @throws java.io.IOException
	 *             return
	 */
	public static BufferedImage scaleByPercentage(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
		// 获取原始图像透明度类型
		int type = inputImage.getColorModel().getTransparency();
		int width = inputImage.getWidth();
		int height = inputImage.getHeight();
		// 开启抗锯齿
		RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		// 使用高质量压缩
		renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		BufferedImage img = new BufferedImage(newWidth, newHeight, type);
		Graphics2D graphics2d = img.createGraphics();
		graphics2d.setRenderingHints(renderingHints);
		graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
		graphics2d.dispose();
		return img;
	}

}
